<template>
  <div class="app-container">
    <div>
      <el-input
        v-model="appViewModel.ModuleName"
        size="small"
        placeholder="模块名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="queryAppVersion"
      />
      <!-- <el-input v-model="appViewModel.ModuleNumber" size="small" placeholder="模块编号" style="width: 200px;"
      class="filter-item" @keyup.enter.native="queryAppVersion" />-->
      <el-input
        v-model="appViewModel.OprateName"
        size="small"
        placeholder="操作名称"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="queryAppVersion"
      />
      <el-input
        v-model="appViewModel.Code"
        size="small"
        placeholder="操作编码"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="queryAppVersion"
      />
      <el-input
        v-model="appViewModel.Identification"
        size="small"
        placeholder="标识"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="queryAppVersion"
      />
      <el-select v-model="appViewModel.UserType" size="small" placeholder="请选择用户类型">
        <el-option
          v-for="item in userTypeOptionList"
          :key="item.TypeCode"
          :label="item.label"
          :value="item.TypeCode"
        ></el-option>
      </el-select>
      <el-button type="primary" size="small" @click="queryAppVersion" icon="el-icon-search">查询</el-button>
      <el-button type="primary" size="small" @click="handleAdd" icon="el-icon-plus">新增</el-button>
      <el-button type="primary" size="small" @click="refreshAppVersion" icon="el-icon-refresh">刷新</el-button>
    </div>
    <el-table
      v-loading="loading"
      :data="AppVersionList"
      :header-cell-style="{background:'#eef1f6',color:'#606266'}"
      style="width: 100%;margin-top:30px;"
      border
      @sort-change="sortChange"
    >
      <el-table-column label="模块名称" align="center" prop="ModuleName">
        <template slot-scope="scope">{{ scope.row.ModuleName }}</template>
      </el-table-column>
      <el-table-column label="用户类型" align="center" prop="UserType">
        <template slot-scope="scope">{{ scope.row.UserType | statusFilter }}</template>
      </el-table-column>
      <el-table-column label="操作名称" align="center" prop="OprateName">
        <template slot-scope="scope">{{ scope.row.OprateName }}</template>
      </el-table-column>
      <el-table-column label="操作编码" align="center" prop="Code">
        <template slot-scope="scope">{{ scope.row.Code }}</template>
      </el-table-column>
      <el-table-column label="标识" align="center" prop="Identification">
        <template slot-scope="scope">{{ scope.row.Identification }}</template>
      </el-table-column>
      <el-table-column label="积分" align="center" prop="Credit">
        <template slot-scope="scope">{{ scope.row.Credit }}</template>
      </el-table-column>

      <el-table-column label="发布时间" align="center" sortable="CreateTime" prop="CreateTime">
        <template slot-scope="scope">{{ scope.row.CreateTime}}</template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template slot-scope="scope">
          <el-button type="text" size="small" @click="handleEdit(scope)" icon="el-icon-edit">编辑</el-button>
          <el-button type="text" size="small" @click="handleDelete(scope)" icon="el-icon-delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页组件：https://element.eleme.cn/#/zh-CN/component/pagination -->
    <div class="block" style="float:right;margin-top:15px;" v-if="appViewModel.total>0">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="appViewModel.page"
        :page-sizes="[10, 20, 30, 40,100]"
        :page-size="appViewModel.pageSize"
        @prev-click="lastPage"
        @next-click="nextPage"
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="appViewModel.total"
      ></el-pagination>
    </div>

    <el-dialog
      :visible.sync="dialogVisible"
      :title="dialogType==='edit'?'编辑':'新增'"
      width="60%"
      top="12vh"
      :close-on-click-modal="false"
    >
      <el-form
        :model="model"
        ref="model"
        :rules="rules"
        label-width="80px"
        label-position="right"
        style="width: 90%;"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="模块名称" prop="ModuleName">
              <el-input v-model="model.ModuleName" placeholder="模块名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模块编号" prop="ModuleNumber">
              <el-input v-model="model.ModuleNumber" placeholder="模块编号" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="操作名称" prop="OprateName">
              <el-input v-model="model.OprateName" placeholder="操作名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="操作编码" prop="Code">
              <el-input v-model="model.Code" placeholder="操作编码" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="标识" prop="Identification">
              <el-input v-model="model.Identification" placeholder="标识" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="积分" prop="Credit">
              <el-input-number
                style="width: 100%;"
                v-model="model.Credit"
                :precision="1"
                :step="0.1"
              ></el-input-number>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="用户类型" prop="UserType">
              <el-select v-model="model.UserType" style="width:100%" placeholder="请选择用户类型">
                <el-option
                  v-for="item in userTypeList"
                  :key="item.TypeCode"
                  :label="item.label"
                  :value="item.TypeCode"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="Note">
              <el-input type="textarea" :rows="3" v-model="model.Note" placeholder="备注" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" :loading="loading" @click="confirmModel">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 100%;
}

.avatar-uploader .el-upload:hover {
  border-color: #409eff;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}

.avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.v-modal {
  z-index: 2000 !important;
}
</style>

<script>
import { getModelList, addModel, updateModel, deleteModel } from "@/api/integralConfig";
import { deepClone } from "@/utils";
import { GetDictionaryByPCode } from "@/api/dictionary";
import Tinymce from "@/components/Tinymce";
const defaultModel = {
  Id: "",
  ModuleName: "",
  ModuleNumber: "",
  UserType: "",
  UserTypeName: "",
  Code: "",
  OprateName: "",
  Identification: "",
  Credit: "",
  Note: "",
  Creater: "",
  CreateTime: "",
  Modifyer: "",
  ModifyTime: ""
};
export default {
  components: { Tinymce },
  filters: {
    statusFilter(type) {
      const userTypeList = [
        { TypeCode: 'ALL', label: '全部' },
        { value: 'USER', label: '用户' },
        { value: 'TEACHER', label: '讲师' },
        { value: 'STUDENT', label: '学生' }
      ]
      return userTypeList.filter(u => u.TypeCode == type)[0].label
    }
  },
  data() {
    return {
      appViewModel: {
        page: 1,
        pageSize: 10,
        total: 0,
        ModuleName: "",
        ModuleNumber: "",
        Code: "",
        OprateName: "",
        Identification: "",
        UserType: "",
        OrderBy: "CreateTime", //排序字段
        IsAsc: true,//是否升序
        SortDir: "DESC"
      },
      dialogVisible: false,
      dialogType: "",
      model: Object.assign({}, defaultModel),
      AppVersionList: [],
      AppVersionTypeList: [],
      userTypeList: [
        { TypeCode: 'ALL', label: '全部' },
        { value: 'USER', label: '用户' },
        { value: 'TEACHER', label: '讲师' },
        { value: 'STUDENT', label: '学生' }
      ],
      userTypeOptionList: [
        { TypeCode: '', label: '请选择' },
        { TypeCode: 'ALL', label: '全部' },
        { value: 'USER', label: '用户' },
        { value: 'TEACHER', label: '讲师' },
        { value: 'STUDENT', label: '学生' }
      ],
      apiPre: process.env.VUE_APP_BASE_API,
      actionUrl: "",
      loading: false,
      rules: {
        ModuleName: [
          { required: true, message: "请输入模块名称", trigger: "blur" },
          {
            min: 1,
            max: 50,
            message: "长度在 1 到 50 个字符",
            trigger: "blur"
          }
        ],
        ModuleNumber: [{ required: true, message: "请输入模块编号", trigger: "blur" }],
        UserType: [{ required: true, message: "请选择用户类型", trigger: "blur" }],
        Code: [{ required: true, message: "请输入操作编码", trigger: "blur" }],
        OprateName: [{ required: true, message: "请输入操作名称", trigger: "blur" }],
        Identification: [{ required: true, message: "请输入标识", trigger: "blur" }],
        Credit: [{ required: true, message: "请输入积分", trigger: "blur" }]
      }
    };
  },
  computed: {
    // 计算属性，只要相关联的值没有改变，直接返回，不再进行计算，与方法区别，缓存
  },
  created() {
    // 实例创建完成后执行的代码
    this.getAppVersionList(this.appViewModel);
    this.actionUrl = this.apiPre + "/Upload/UploadFiles";
    // this.getDictionaryByPCode()
  },
  methods: {
    async getDictionaryByPCode() {
      const res = await GetDictionaryByPCode('UserType');
      this.userTypeList = res.data;
      this.userTypeList.unshift({ TypeCode: 'ALL', label: '全部' })
    },
    async getAppVersionList(appViewModel) {
      this.loading = true
      const res = await getModelList(appViewModel);
      if (res.data) {
        this.appViewModel.total = res.data.TotalCount;
      }
      this.AppVersionList = res.data.Items;
      this.loading = false
    },
    closeDialog() { },
    queryAppVersion() {
      this.appViewModel.page = 1
      this.getAppVersionList(this.appViewModel);
    },
    refreshAppVersion() {
      this.appViewModel.AppCode = "";
      this.appViewModel.ModuleName = ""
      this.appViewModel.ModuleNumber = ""
      this.appViewModel.Code = ""
      this.appViewModel.OprateName = ""
      this.appViewModel.Identification = ""
      this.appViewModel.UserType = ""
      this.appViewModel.page = 1
      this.getAppVersionList(this.appViewModel);
    },
    sortChange(data) {
      const { prop, order } = data;
      this.appViewModel.OrderBy = prop;
      if (prop == null || prop == "") this.appViewModel.OrderBy = "CreateTime";
      if (order === "ascending") {
        this.appViewModel.IsAsc = true;
      } else {
        this.appViewModel.IsAsc = false;
      }
      this.queryAppVersion();
    },
    lastPage(val) {
      this.appViewModel.page = val;
    },
    nextPage(val) {
      this.appViewModel.page = val;
    },
    handleChange(value) {
      console.log(value);
    },
    handleSizeChange(val) {
      this.appViewModel.pageSize = val;
      this.getAppVersionList(this.appViewModel);
    },
    handleCurrentChange(val) {
      this.appViewModel.page = val;
      this.getAppVersionList(this.appViewModel);
    },
    handlePublish(scope, status) {
      var str = "下架";
      if (status == 1) str = "上架";
      this.$confirm("确认" + str + scope.row.Title + "?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          await publishModel(scope.row.Id, status);
          this.$notify({
            title: "成功",
            type: "success",
            message: "操作成功!"
          });
          this.queryAppVersion();
        })
        .catch(err => {
          console.error(err);
        });
    },
    handleAdd() {
      this.model = deepClone(defaultModel);
      this.model.UserType = 'ALL'
      this.$nextTick(() => {
        this.$refs["model"].clearValidate(); //清空上次的错误验证提示
      });
      this.dialogType = "new";
      this.dialogVisible = true;
    },
    handleEdit(scope) {
      this.dialogType = "edit";
      this.dialogVisible = true;
      this.model = deepClone(scope.row);
      this.$nextTick(() => {
        this.$refs["model"].clearValidate(); //清空上次的错误验证提示
      });
    },
    async confirmModel() {
      //如果把验证失败弹出提示代码放在validate里面则不会弹出错误提示，直接走下面的更新操作代码
      var v;
      this.$refs["model"].validate(valid => {
        v = valid;
      });
      if (!v) {
        return false;
      }
      const isEdit = this.dialogType === "edit";
      if (isEdit) {
        await updateModel(this.model);
      } else {
        await addModel(this.model);
        this.appViewModel.page = 1;
      }
      // await addModel(this.model);
      this.getAppVersionList(this.appViewModel);
      this.model = deepClone(defaultModel);
      this.dialogVisible = false;
      this.$notify({
        title: "成功",
        type: "success",
        message: "操作成功!"
      });
    },
    handleDelete({ $index, row }) {
      this.$confirm("确认删除?", "提示", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          this.loading = true
          await deleteModel(row.Id);
          this.$notify({
            title: "成功",
            type: "success",
            message: "操作成功!"
          });
          this.getAppVersionList(this.appViewModel);
        })
        .catch(err => {
          console.error(err);
        });
    },
    handleAvatarSuccess(res, file) {
      //图片上传成功响应方法
      this.model.AppUrl = res.data;
      this.$notify({
        title: "成功",
        message: "上传完成!",
        type: "success",
        duration: 3000
      });
      this.loading = false
    },
    beforeAvatarUpload(file) {
      this.loading = true
      var fileName = file.name || ''
      var ext = fileName.split('.')[fileName.split('.').length - 1]
      if (ext !== "apk" && ext !== "ipa") {
        this.$notify({
          title: "失败",
          message: "上传资源只能是 .apk/.ipa 格式的文件!",
          type: "info",
          duration: 3000
        });
        this.loading = false
        return false
      }
      // const isImg = file.type === '.apk' || file.type === '.ipa';
      // const isLt2M = file.size / 1024 / 1024 < 5;

      // if (!isImg) {
      //   this.$notify({
      //     title: "失败",
      //     message: "上传头像图片只能是 JPG/JPEG/PNG 格式!",
      //     type: "error",
      //     duration: 3000
      //   });
      //   return false
      // }
      // if (!isLt2M) {
      //   this.$notify({
      //     title: "失败",
      //     message: "上传头像图片大小不能超过 5MB!",
      //     type: "error",
      //     duration: 3000
      //   });
      //   return false
      // }
      return true;
    }
  }
};
</script>